from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded

from app.utils.rate_limiter import limiter # Import the main limiter instance
from app.routers import auth, users, credits, images, gallery, admin

# Initialize FastAPI app
app = FastAPI(
    title="AI Image Gen Backend",
    description="Backend API for AI Image Generation service with credits and gallery.",
    version="0.1.0"
)

# Add Rate Limiter state and handler
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

# Add CORS middleware (adjust origins as needed for your frontend)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"], # Allows all origins for simplicity, restrict in production!
    allow_credentials=True,
    allow_methods=["*"], # Allows all methods
    allow_headers=["*"], # Allows all headers
)

# Include routers
app.include_router(auth.router, prefix="/auth")
app.include_router(users.router)
app.include_router(credits.router)
app.include_router(images.router)
app.include_router(gallery.router)
app.include_router(admin.router)

# Basic root endpoint
@app.get("/", tags=["Root"])
async def read_root():
    return {"message": "Welcome to the AI Image Gen API"}

# Optional: Add a generic exception handler for unhandled errors
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
    # Log the exception details here in a real app
    # import logging
    # logging.exception("Unhandled exception occurred")
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content={"detail": "An unexpected internal server error occurred."},
    )

# Optional: Add database initialization logic if needed (e.g., create tables on startup)
# from app.db.base import Base
# from app.db.session import engine
# @app.on_event("startup")
# async def on_startup():
#     async with engine.begin() as conn:
#         # Use this only for initial development or if not using migrations
#         # await conn.run_sync(Base.metadata.drop_all)
#         await conn.run_sync(Base.metadata.create_all)
